package maquina.interfaz.io.impl;

import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.rmi.AlreadyBoundException;
import java.rmi.RemoteException;
import java.rmi.registry.Registry;
import java.rmi.server.UnicastRemoteObject;
import java.util.List;

import javax.swing.JButton;
import javax.swing.JFrame;

import maquina.gestor.flujo.InterfaceGestorTarjeta;
import maquina.interfaz.io.InterfaceLectorTarjeta;

public class LectorTarjetaStub extends UnicastRemoteObject implements InterfaceLectorTarjeta {

	
	private static final long serialVersionUID = 6739487575961427532L;
	
	Registry registry;
	private static final int port = 1010;
	public JFrame visual;
	
	protected LectorTarjetaStub() throws RemoteException, AlreadyBoundException {
		super();
		registry = java.rmi.registry.LocateRegistry.createRegistry(port);
		registry.bind("LectorTarjetaMAQUINA", this);
		visual = new JFrame();
		visual.setBounds(300, 300, 200, 200);
		JButton jb = new JButton("Ingresar tarjeta");
		visual.add(jb);
		visual.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		jb.addMouseListener(new MouseAdapter(){
			public void mouseClicked(MouseEvent arg0) {
					InterfaceGestorTarjeta gestor;
					try {
						gestor = (InterfaceGestorTarjeta) registry.lookup("GestorTarjeta");
						gestor.ingresarTarjeta();
					} catch (Exception e) {
						e.printStackTrace();
					}
			}
		});
		visual.setVisible(true);
	}

	public boolean ping() {

		return true;
	}

	public void escribirTarjeta(List<String> candidatos) {
		
		try {
			
		    BufferedWriter out = new BufferedWriter(new FileWriter("tarjeta.txt"));
		    
		    String str = "";
		    
		    for(String candidato: candidatos){
		    
		    	str += candidato + "\n";
		    }
		    
		    out.write(str);
		    
		    out.close();
		
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public static void main(String[] args) {
		 try {
			new LectorTarjetaStub();
		} catch (Exception e) {
			e.printStackTrace();
		}
	 }


}
